package com.cskaoyan.app.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.UUID;




public class FileUtil {


    private static String root;

    @Value("${spring.web.resources.static-locations}")
    public void setRoot(String root) {
        FileUtil.root = root;
    }

    public static String uri = "http://localhost:8083/";


    public static String url;

    public static String filepath;

    public static String upLoad(MultipartFile multipartFile) {
        return upLoad(multipartFile, null);
    }

    public static String upLoad(MultipartFile multipartFile, String path) {
        if (path == null) {
            path = "";
        }
        root = updateRoot(root);
        //uri = updateUri(uri);
        path = updatePath(path);
        String originalFilename = multipartFile.getOriginalFilename();
        UUID uuid = UUID.randomUUID();
        String filename = uuid + originalFilename;

        System.out.println("********");
        System.out.println("********");
        filepath = updateFilepath(root + path);
        System.out.println("********");
        System.out.println(filepath);
        System.out.println("********");
        File file = new File(filepath, filename);

        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        url = uri + path + filename;
        System.out.println("********");
        System.out.println(url);
        System.out.println("********");
        return url;
    }

    private static String updateRoot(String root) {
        return root.trim().replace("file:", "").trim();
    }

    private static String updatePath(String path) {
        if ("".equals(path)) {
            return path;
        }
        path = path.trim();
        //去除path首个/
        if (path.indexOf("/") == 0) {
            path = path.substring(1);
        }
        //增加path最后的/
        if ((path.indexOf("/", path.length() - 1)) == -1) {
            path += "/";
        }
        return path;
    }

    private static String updateFilepath(String filepath){
        return filepath.replace("/","\\");
    }

    private static String updateUri(String uri) {
        return uri.substring(0, uri.length() - 2);
    }



}
